package control;

import entity.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Properties;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();

    /**
     * 微信登录（拉取授权）
     * @param req
     * @param resp
     */
    public void to_wx_login(HttpServletRequest req, HttpServletResponse resp)  {
        try {
            // 加载配置文件
            Properties prop=new Properties();
            prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));

            String appid = prop.getProperty("wx.AppID");

            //微信授权成功后的回调地址
            String redirect_uri = prop.getProperty("wx.redirect_uri");

            //Step1：获取Authorization Code
            String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                    "&appid=" + appid +
                    "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                    "&scope=snsapi_login";

            // 重定向到微信登录指定的地址进行微信登录授权,授权成功后返回code（响应一张二维码）
            resp.sendRedirect(url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 校检用户名
     *
     * @param req
     * @param resp
     */
    public void checkUsername(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String username = req.getParameter("username");
            User user = userService.findByUsername(username);

            // 设置响应类型
            resp.setContentType("application/json;charset=utf8");
            if (user == null) {
                resp.getWriter().write("0");
            } else {
                resp.getWriter().write("1");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 校检邮箱
     *
     * @param req
     * @param resp
     */
    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            User user = userService.findByEmail(email);
            // 设置响应类型
            resp.setContentType("text/html;charset=utf8");
            if (user == null) {
                resp.getWriter().write("0");
            } else {
                resp.getWriter().write("1");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    /**
     * 注册，将数据插入数据库
     * @param request
     * @param response
     */
    public void register( HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //获取前端传送的参数
        Map<String, String> param = BaseServlet.getParam(request);

        //调用业务层
        userService.register(param);

        //转发到对应页面
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    /**
     * 登录，去数据库中比对信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void login( HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        HttpSession session = request.getSession();

        // 2.校验验证码是否一致
        String sessionCode = (String) session.getAttribute("sessionCode");

        if (!sessionCode.equals(request.getParameter("checkCode"))) {
            //验证码错误
            session.setAttribute("error", "验证码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);

            // 结束方法的执行
            return;
        }

        //获取前端传送的参数
        Map<String, String> param = BaseServlet.getParam(request);

        //调用业务层
        User user = userService.login(param);

        if (user == null) {
            //用户名或者密码错误
            session.setAttribute("error", "用户名或者密码错误");
            request.getRequestDispatcher("/index.jsp").forward(request, response);

        }else {
            //签发cookie
            String rememberMe = request.getParameter("rememberMe");
            if ("1".equals(rememberMe)) {
                //勾选了记住我
                Cookie cookie = new Cookie("userId", user.getId()+"");
                //设置携带路径
                cookie.setPath("/");
                //持久化
                cookie.setMaxAge(60*60*24*7);
                //添加到响应头
                response.addCookie(cookie);


            }else {

            }
            //删除错误信息
            session.removeAttribute("error");
            //将登录用户的信息存入session
            session.setAttribute("loginUser", user);
            //正确登录，重定向
            response.sendRedirect("/html/home.jsp");
        }

    }
}
